﻿using AutoMapper;
using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interfance;
using B.S.BasicData.Write.Application.Common.Menu;
using MediatR;
using System.Transactions;

namespace B.S.BasicData.Write.Application.Handler.Menu
{
    public class CreateMenuHandler : IRequestHandler<CreateMenuCommon, ApiResult<int>>
    {
        private readonly IBaseRepository<menuModel> menuRepo;
        private readonly IMapper mapper;

        public CreateMenuHandler(IBaseRepository<menuModel> menuRepo,IMapper mapper)
        {
            this.menuRepo = menuRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(CreateMenuCommon request, CancellationToken cancellationToken)
        {
            ApiResult<int> res=new ApiResult<int>();

            var info = menuRepo.GetAll().Where(x=>x.MenuName==request.MenuName&&x.IsDeleted==false&&x.ParentId==request.ParentId).FirstOrDefault();

            if(info!=null)
            {
                res.Code=ApiEnum.Error;
                res.Message = "用一级菜单不允许名称重复";
                return Task.FromResult(res);
            }
            var model= mapper.Map<menuModel>(request);
            if (model.ParentId == null)
            {
                model.ParentId = 0;
            }
            var r = 0;
            using (TransactionScope tran=new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                r= menuRepo.Add(model).Result;
                tran.Complete();
            }
           
           if(r>0)
            {
                res.Code = ApiEnum.Success;
                res.Message = "添加成功";
                return Task.FromResult(res);
            }
            else
            {
                res.Code = ApiEnum.Error;
                res.Message = "添加失败";
                return Task.FromResult(res);
            }
 


        }
    }
}
